package com.sunnyatwal.kettlebell;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sunnyatwal.kettlebell.db.WorkoutDatabase;
import com.sunnyatwal.kettlebell.db.WorkoutDatabaseSingleton;
import com.sunnyatwal.kettlebell.model.Exercise;

public class ManageWorkoutActivity extends SherlockActivity {
	
	private final static String TAG = "ManageWorkoutActivity";
	
	private final static String INTENT_NAME_WORKOUT = "workout";
	private final static int REQUEST_CODE_ADD_WORKOUT = 200;
	private final static int REQUEST_CODE_EDIT_WORKOUT = 100;
	private final static int INVALID_LIST_INDEX = -1;
	
	private int mSelectedItemIndex = INVALID_LIST_INDEX;
	
	private WorkoutDatabase mdatabase;
	
	private ActionMode mMode;
	
	
	@Override 
	protected void onStart() {
		Log.i(TAG, "onStart");
		super.onStart();
	}
	
	
	@Override
	protected void onStop() {
    	Log.i(TAG, "onStop");
    	super.onStop();
    }
	
	
	@Override
	protected void onRestart() {
		Log.i(TAG, "onRestart");
		super.onRestart();
	}
	
	
	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();		
		populateListFromDatabase();			    			
	}
	
	
	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy");
		mdatabase.close();
		super.onDestroy();		
	}
	
	
	@Override
    public void onBackPressed() {
    	Log.i(TAG, "onBackPressed");    	
		mdatabase.close();
		super.onBackPressed();
    }
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.i(TAG, "onCreate");
    	
    	super.onCreate(savedInstanceState);
    	
    	setContentView(R.layout.activity_manage_workout);
    	
    	getActionBar().setDisplayHomeAsUpEnabled(false);
    	getActionBar().setDisplayShowTitleEnabled(false);
    	
    	MainMenuHelper mmhelper = MainMenuHelper.getInstance();
        mmhelper.createMenuButtons(this);
        
        try {
			mdatabase = WorkoutDatabaseSingleton.getDatabase(this);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
    }
    
	
    @Override
    public void onContentChanged() {
    	Log.i(TAG, "onContentChanged");
    	
    	super.onContentChanged();
    	
    	ListView workoutListView = (ListView) findViewById(R.id.manage_workout_ListView);		
    	View empty = findViewById(R.id.manage_workout_ListView_empty);
		workoutListView.setEmptyView(empty);				
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	Log.i(TAG, "onCreateOptionsMenu");
    	
    	getSupportMenuInflater().inflate(R.menu.activity_manage_workout, menu);    
        return super.onCreateOptionsMenu(menu);
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    	
    	Log.i(TAG, "onOptionsItemSelected");
    	
    	super.onOptionsItemSelected(item);
    	        
        switch (item.getItemId()) {
        
        	case android.R.id.home:
        		finish();
        		break;
        	
        	case R.id.menu_add_workout:
        		startEditActivityForResult();
        		break;
        }
        
        return true;
    }
    
    
    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent intent) {
    	Log.i(TAG, "onActivityResult");
    	
    	boolean bSaved = false;
    	
    	if (resultCode == Activity.RESULT_OK) {
    		if (requestCode == REQUEST_CODE_ADD_WORKOUT || requestCode == REQUEST_CODE_EDIT_WORKOUT) {	        
	            if (intent.hasExtra(INTENT_NAME_WORKOUT)) {
	            	
	        		Exercise workoutResult = intent.getParcelableExtra(INTENT_NAME_WORKOUT);
	        		            	
	        		if (workoutResult != null) {
		            	if (requestCode == REQUEST_CODE_EDIT_WORKOUT && mSelectedItemIndex > INVALID_LIST_INDEX)
		        			bSaved = mdatabase.update(mSelectedItemIndex, workoutResult);
		            	else if (requestCode == REQUEST_CODE_ADD_WORKOUT)
		            		bSaved = mdatabase.add(workoutResult);
	        		}
	            }
	        }
    	}
    	
    	String sMessage = bSaved ? getString(R.string.string_workout_saved) : 
			getString(R.string.string_workout_not_saved);
    	
    	Toast.makeText(ManageWorkoutActivity.this, sMessage, Toast.LENGTH_SHORT).show();
    	
    	//Need to clear selected index when returning from prev. activity
    	mSelectedItemIndex = INVALID_LIST_INDEX;
    }
    
    
    /**
     * Starts EditWorkoutActivity with the provided workout
     * @param e the exercise to be edited
     */
  	private void startEditActivityForResult(Exercise e) {
  		Log.i(TAG, "startEditActivityForResult");
  		
  		Intent intent = new Intent(this, EditWorkoutActivity.class);		
      	intent.putExtra(INTENT_NAME_WORKOUT, e);
      	startActivityForResult(intent, REQUEST_CODE_EDIT_WORKOUT);
  	}
  	
  	
  	/**
  	 * Starts EditWorkoutActivity activity for a new workout
  	 */
  	private void startEditActivityForResult() {
  		Log.i(TAG, "startEditActivityForResult");
  		
  		Intent intent = new Intent(this, EditWorkoutActivity.class);
      	startActivityForResult(intent, REQUEST_CODE_ADD_WORKOUT);
  	}
  	
  	
  	/**
  	 * Starts ClockActivity with chosen workout
  	 */
  	private void startClockActivity(Exercise e) {
  		Log.i(TAG, "startClockActivity");
  		
  		Intent intent = new Intent(ManageWorkoutActivity.this, ClockActivity.class);                		
    	intent.putExtra("exercise", e);
		startActivity(intent);
  	}
  	
  	
	/**
	 * Fills the workout listview adapter with workouts from database
	 * @return the new size of the list adapter
	 */
	private boolean populateListFromDatabase() {		
		Log.i(TAG, "populateListFromDatabase");	
		
		ArrayList<Exercise> exercises = (ArrayList<Exercise>) mdatabase.getSortedList();		
		
		if (exercises.size() < 1) {
			Log.i(TAG, "No entries found in database");
		}
		
		ExerciseAdapter adapter = new ExerciseAdapter(this, R.layout.exercise_row, exercises);
        
        final ListView listview = (ListView) findViewById(R.id.manage_workout_ListView);        
        listview.setAdapter(adapter);
        
        listview.setOnItemClickListener(new OnItemClickListener() {
        	
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		
        		view.setSelected(true);
        		
        		mSelectedItemIndex = position;
        		
        		mMode = startActionMode(new ActionModeListItemSelect());
        		
        		//clear the selected row when clicking the checkmark 'done' button
        		int doneButtonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");				
        		View doneButton = findViewById(doneButtonId);				
				doneButton.setOnClickListener(new View.OnClickListener() {

					@Override					
				    public void onClick(View v) {
						finishActionMode(true);
				    }
				});        	        		
            }
        });
                
        adapter.notifyDataSetChanged();
		
        return adapter.getCount() > 0;       
	}
	
	
	private boolean deleteWorkout() {
		Log.i(TAG, "deleteWorkout");
		
		if (mSelectedItemIndex > INVALID_LIST_INDEX) {    		    		
			if (mdatabase.deleteSorted(mSelectedItemIndex)) {
				populateListFromDatabase();
				return true;
			}
		}
		else {
			Log.i(TAG, "Invalid item selected");
		}
		
		return false;
	}
	
	
	public void finishActionMode(boolean clearListIndex) {
    	Log.i(TAG, "finishActionMode");
    	
    	ListView listview = (ListView)findViewById(R.id.manage_workout_ListView);
    	listview.clearChoices();
    	listview.requestLayout();
    	mMode.finish();
    	
    	if (clearListIndex) {
    		mSelectedItemIndex = INVALID_LIST_INDEX;
    	}
    }
	
	
	/**
	 * ActionMode gets called whenever a list item is selected
	 */
    private final class ActionModeListItemSelect implements ActionMode.Callback {
    	
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {       	
            getSupportMenuInflater().inflate(R.menu.activity_manage_workout_action_mode, menu);        	             
            return true;
        }
        
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
        
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            
        	if (mSelectedItemIndex > INVALID_LIST_INDEX) {
        			        	
        		Exercise selectedExercise = mdatabase.getSortedEntry(mSelectedItemIndex);
        		
                switch (item.getItemId()) {
                
                	case R.id.menu_play_workout:
                		Log.i(TAG, "playing workout");
                		
                		startClockActivity(selectedExercise);                		                	
                		finishActionMode(true);
    	    			break;
                	
                	case R.id.menu_edit_workout:
                		Log.i(TAG, "editing workout");
                		
                		startEditActivityForResult(selectedExercise);
                		finishActionMode(false);	    			
    	    			break;
                	
                	case R.id.menu_delete_workout:
                		Log.i(TAG, "deleting workout");
                		
                		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(ManageWorkoutActivity.this);
            			
                		helpBuilder.setTitle(getText(R.string.string_delete) + " " + 
                					selectedExercise.getTitle() + getText(R.string.string_question_mark));
                		                		
                		helpBuilder.setNegativeButton(getString(R.string.string_confirm),
                				new DialogInterface.OnClickListener() {
                    	    		public void onClick(DialogInterface dialog, int which) {
                    	    			deleteWorkout();
                    	    			finishActionMode(true);
                    	    	    }
                    	});
                    	
                    	helpBuilder.setNeutralButton(getString(R.string.string_cancel),
                    			new DialogInterface.OnClickListener() {
                    	    		public void onClick(DialogInterface dialog, int which) {
                    	    			finishActionMode(true);
                    	    	    }
                    	});
                    	        		
                		AlertDialog helpDialog = helpBuilder.create();
                    	helpDialog.show();                		
                    	break;                	
                }	        		        		        		
        	}
        	else {
        		Log.i(TAG, "No list items selected");
        	}
        	                                   
            return true;
        }

        
        public void onDestroyActionMode(ActionMode mode) {
        	Log.i(TAG, "onDestroyActionMode");
        }        
    }
    
    
}





